package node_login

import (
	"reflect"
	"sanguo/cluster"
	codecs "sanguo/codec/cs"

	"github.com/golang/protobuf/proto"
	"github.com/sniperHW/kendynet"
)

type handler func(kendynet.StreamSession, *codecs.Message)

var gDispatcher dispatcher

type dispatcher struct {
	handlers map[string]handler
}

func (this *dispatcher) Register(msg proto.Message, h handler) {
	msgName := reflect.TypeOf(msg).String()
	if nil == h {
		return
	}
	_, ok := this.handlers[msgName]
	if ok {
		return
	}

	this.handlers[msgName] = h
}

func (this *dispatcher) Dispatch(session kendynet.StreamSession, msg *codecs.Message) {
	if nil != msg {
		name := msg.GetName()
		handler, ok := this.handlers[name]
		if ok {
			//交给cluster的任务队列单线程执行
			cluster.PostTask(func() {
				handler(session, msg)
			})
		}
	}
}

func (this *dispatcher) OnClose(session kendynet.StreamSession, reason string) {
	Infof("client close:%s\n", reason)
}

func (this *dispatcher) OnNewClient(session kendynet.StreamSession) {
	Infof("new client\n")
}
